package com.mldkhn.led_controller;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;


public class Fragment_Vielfarbe extends Fragment implements OnClickListener, OnSeekBarChangeListener {

	
	private static Button[] btnVielfarbe = new Button[20];
	private static int[] btnId =   {R.id.btnVielfarbe1, R.id.btnVielfarbe2, R.id.btnVielfarbe3, R.id.btnVielfarbe4, 
									R.id.btnVielfarbe5, R.id.btnVielfarbe6, R.id.btnVielfarbe7, R.id.btnVielfarbe8, 
									R.id.btnVielfarbe9, R.id.btnVielfarbe10, R.id.btnVielfarbe11, R.id.btnVielfarbe12,
									R.id.btnVielfarbe13, R.id.btnVielfarbe14, R.id.btnVielfarbe15, R.id.btnVielfarbe16,
									R.id.btnVielfarbe17, R.id.btnVielfarbe18, R.id.btnVielfarbe19, R.id.btnVielfarbe20};
	private static Integer[] Farben = new Integer[20];
	private static SeekBar scrVielfarbeDelay;
	private static TextView lblVielfarbeDelay;
	private static Button btnVielfarbeStart, btnVielfarbeStop;
	private static String strMany = "MANY";
	private static String strStop = "OFF";
	private int progressDelay = 0;
	
	private Socket socket;

	private static int SERVERPORT;
	private static String SERVER_IP;
	Thread socketThread;
	
	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
	    View v = inflater.inflate(R.layout.fragment_vielfarbe, null);
	    for(int i = 0; i < 20; i++)
	    {
		    btnVielfarbe[i] = (Button) v.findViewById(btnId[i]);
		    btnVielfarbe[i].setOnClickListener(this);
		    if(Farben[i] != null)
		    {
		    	Drawable x = btnVielfarbe[i].getBackground();
		    	x.setColorFilter(Farben[i], PorterDuff.Mode.OVERLAY);
		    	float[] hsv = new float[3];
		    	Color.colorToHSV(Farben[i], hsv);
		    	if(hsv[2] > 0.5)
		    		btnVielfarbe[i].setTextColor(Color.BLACK);
		    	else
		    		btnVielfarbe[i].setTextColor(Color.WHITE);
		    }
	    }
	    btnVielfarbeStart = (Button) v.findViewById(R.id.btnVielfarbeStart);
	    btnVielfarbeStart.setOnClickListener(this);
	    btnVielfarbeStop = (Button) v.findViewById(R.id.btnVielfarbeStop);
	    btnVielfarbeStop.setOnClickListener(this);
	    lblVielfarbeDelay = (TextView) v.findViewById(R.id.lblVielfarbeDelay);
	    lblVielfarbeDelay.setText(" 0.0 s");
	    scrVielfarbeDelay = (SeekBar) v.findViewById(R.id.scrVielfarbeDelay);
	    scrVielfarbeDelay.setOnSeekBarChangeListener(this);
		try{
			SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
			SERVER_IP = mySharedPreferences.getString("edittext_ip", "");
			SERVERPORT = Integer.parseInt(mySharedPreferences.getString("edittext_port", ""));
			socketThread = new Thread(new ClientThread());
			socketThread.start();
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream())),
					true);
			out.println("HELLO");
			out.close();
			socketThread.interrupt();
			socketThread = null;
			
			} 
			  catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
	    return v;
		}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		for(int j = 0; j < 20; j++)
		{
			if(v.getId() == btnId[j]){
				intent.setClass(getActivity(), Activity_Colorpicker.class);
				if(Farben[j] != null)
				intent.putExtra("Color", Farben[j]);
				startActivityForResult(intent,j);
				break;
			}				
		}
		if(v.getId() == R.id.btnVielfarbeStart)
		{
			try{
				SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
				SERVER_IP = mySharedPreferences.getString("edittext_ip", "");
				SERVERPORT = Integer.parseInt(mySharedPreferences.getString("edittext_port", ""));
				socketThread = new Thread(new ClientThread());
				socketThread.start();
				PrintWriter out = new PrintWriter(new BufferedWriter(
						new OutputStreamWriter(socket.getOutputStream())),
						true);
				String Output, Delay;
				Delay = String.format("%02d", progressDelay);
				int count = 0;
				for(int i = 0; i < 20; i++)
				{
					if(Farben[i] != null)
						count++;
				}
				String countString = String.format("%02d", count);
				Output = strMany + "\n" + Delay + "\n" + countString;
				for(int i = 0; i < 20; i++)
				{
					if(Farben[i] != null)
					{
						Output += "\n" + Integer.toHexString(Farben[i]);
					}
				}
				out.println(Output);
				out.close();
				socketThread.interrupt();
				socketThread = null;
				
				} 
				  catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
		if(v.getId() == R.id.btnVielfarbeStop)
		{
			try{
				SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
				SERVER_IP = mySharedPreferences.getString("edittext_ip", "");
				SERVERPORT = Integer.parseInt(mySharedPreferences.getString("edittext_port", ""));
				socketThread = new Thread(new ClientThread());
				socketThread.start();
				PrintWriter out = new PrintWriter(new BufferedWriter(
						new OutputStreamWriter(socket.getOutputStream())),
						true);
				out.println(strStop);
				socketThread.interrupt();
				socketThread = null;
				
				} 
				  catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	    if (resultCode == android.app.Activity.RESULT_OK) {
	    	Bundle bundle = data.getExtras();
	    	processResult(requestCode,bundle.getInt("Color"));   	
	    }
	    if (resultCode == 3)
	    {
	    	Drawable btnFarbe = btnVielfarbe[requestCode].getBackground();
	    	btnFarbe.setColorFilter(null);
	    	int sdk = android.os.Build.VERSION.SDK_INT;
	    	if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
	    	    btnVielfarbe[requestCode].setBackgroundDrawable(btnFarbe);
	    	} else {
	    	    btnVielfarbe[requestCode].setBackground(btnFarbe);
	    	}
	    	btnVielfarbe[requestCode].setTextColor(Color.WHITE);
	    	Farben[requestCode] = null;
	    }
	}
	
	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	private void processResult(int button, int color)
	{
    	Drawable x = btnVielfarbe[button].getBackground();
    	x.setColorFilter(color, PorterDuff.Mode.OVERLAY);
    	Farben[button] = color;
    	float[] hsv = new float[3];
    	Color.colorToHSV(color, hsv);
    	if(hsv[2] > 0.5)
    		btnVielfarbe[button].setTextColor(Color.BLACK);
    	else
    		btnVielfarbe[button].setTextColor(Color.WHITE);
    	int sdk = android.os.Build.VERSION.SDK_INT;
    	if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    	    btnVielfarbe[button].setBackgroundDrawable(x);
    	} else {
    	    btnVielfarbe[button].setBackground(x);
    	}
    }

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		switch(seekBar.getId()){
		case R.id.scrVielfarbeDelay:
			lblVielfarbeDelay.setText(" " + (float)progress/2 + " s");
			progressDelay = progress;
			break;
	}
	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub
		
	}	
	
	class ClientThread implements Runnable {
		
		@Override
		public void run() {
			
			try {
				InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

				socket = new Socket(serverAddr, SERVERPORT);

			} catch (UnknownHostException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}


	}
}
